//
//  PhotoBrowserViewController.m
//  Logistics
//
//  Created by 刘峰 on 2017/12/9.
//  Copyright © 2017年 com.Logistics. All rights reserved.
//

#import "PhotoBrowserViewController.h"
#import "SingleAlubumBrowerViewController.h"
#import "PhotoAlbumViewCell.h"

@interface PhotoBrowserViewController ()

@property (nonatomic, strong) NSMutableArray *alatsList; // 图集


@end

@implementation PhotoBrowserViewController


- (void)goBack {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"相簿";
    // Uncomment the following line to preserve selection between presentations.
    self.navigationController.navigationBarHidden = NO;

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(goBack)];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"PhotoAlbumViewCell" bundle:nil] forCellReuseIdentifier:@"albumCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    WEAKSELF
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    switch (status) {
        case PHAuthorizationStatusNotDetermined:{
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if (status == PHAuthorizationStatusAuthorized) {
                    [weakSelf getPhotoAlbum];
                }else {
                    [[LFAlertBox backgroundAlert] showAlertTitle:@{@"text":@"提示"} content:@{@"text":@"拒绝授权将无法使用相机"} cancleBtn:nil sureBtn:@{@"text":@"狠心拒绝"} completion:^(NSInteger index) {
                        [weakSelf dismissALLViewController];
                    }];
                }
            }];
        }
            break;
            
        case PHAuthorizationStatusAuthorized:{
            [self getPhotoAlbum];
        }
            break;
            
        default:{
            [[LFAlertBox backgroundAlert] showAlertTitle:@"提示" content:@"请开启照片访问权限" cancleText:@"取消" sureText:@"设置" completion:^(NSInteger index) {
                if (index == 0) {
                    [weakSelf dismissALLViewController];
                }else {
                    [NSObject openSystemURL:UIApplicationOpenSettingsURLString];
                }
            }];
        }
            break;
    }
    
}



- (void)getPhotoAlbum {
    // 相机胶卷
    PHFetchResult<PHAssetCollection *> *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    [self sequencePictures:cameraRoll];
    
    // 自定义图集 以及我的照片流
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    [self sequencePictures:assetCollections];
    
    [self.tableView reloadData];
}

#pragma Mark - - 遍历图集（对我的照片流、相机胶卷 进行降序） 其他的升序
- (void)sequencePictures:(PHFetchResult<PHAssetCollection *> *)assetCollections{
    
    for (PHAssetCollection *collection in assetCollections) {
        PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
        
        BrowserObject *model = [[BrowserObject alloc] init];
        model.AssetList   = assets;
        model.albumtitle  = collection.localizedTitle;
        model.albumcount  = assets.count;
        
        NSInteger begin = 0, totalNum;
        BOOL ascending   = NO;
        
        if ([collection.localizedTitle isEqualToString:@"我的照片流"] || [collection.localizedTitle isEqualToString:@"相机胶卷"]) {
            begin    = assets.count - 1;
            totalNum = assets.count > 3 ? assets.count - 3 : 0;
        }else {
            totalNum  = assets.count > 3 ? 3 : assets.count;
            ascending = YES;
        }
        
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.synchronous = YES;

        if (ascending) {
            
            for (NSInteger i = begin; i < totalNum; i++) {
                PHAsset *asset = assets[i];
                
                [[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(KscreenWidth/2, KscreenWidth/2) contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                    [model.images addObject:result];
                }];
            }
            
        }else {
            
            for (NSInteger i = begin; i >= totalNum; i--) {
                PHAsset *asset = assets[i];
                
                [[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(KscreenWidth/2, KscreenWidth/2) contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                    [model.images addObject:result];
                }];

            }

        }
        
        [self.alatsList addObject:model];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.alatsList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PhotoAlbumViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"albumCell" forIndexPath:indexPath];
    cell.line.hidden = indexPath.row == 0 ? NO : YES;
    cell.object = self.alatsList[indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SingleAlubumBrowerViewController *albumVc = [[SingleAlubumBrowerViewController alloc] init];

    BrowserObject *model = self.alatsList[indexPath.row];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [(PHCachingImageManager *)[PHCachingImageManager defaultManager] startCachingImagesForAssets:(NSArray *)model.AssetList targetSize:CGSizeMake(KscreenWidth/2, KscreenWidth/2) contentMode:PHImageContentModeAspectFit options:nil];
    });

    albumVc.bwrObject = model;
    [self.navigationController pushViewController:albumVc animated:YES];
}


-(NSMutableArray *)alatsList {
    if (!_alatsList) {
        _alatsList = [NSMutableArray array];
    }
    return _alatsList;
}

@end
